//
//  OrderViewController.m
//  HuaLang
//
//  Created by iking on 2017/11/20.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "OrderViewController.h"
#import "SGSegmentedControl.h"
#import "OrderTableViewCell.h"
#import "OrderDetailViewController.h"
#import "ShouHouViewController.h"
#import "PingJiaViewController.h"
#import "OrderModel.h"
#import "WuLiuInfoViewController.h"
#import "ZhiFuViewController.h"

@interface OrderViewController ()<UITableViewDelegate,UITableViewDataSource,SGSegmentedControlStaticDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SGSegmentedControlStatic *topSView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"我的订单"];
    [self setUpUI];
    self.currentPage = 1;
    self.pageSize = 20;
    // 请求数据
    [self getGoodsListData];
    // 取消订单通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getResault:) name:@"cancelOrder" object:nil];
    // 确认收货通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getResault:) name:@"confirmOrder" object:nil];
}
- (void)getResault:(NSNotification *)aNotification
{
    [self getGoodsListData];
}
- (void)dealloc
{
    // 注销通知
    NSLog(@"注销通知");
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cancelOrder" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"confirmOrder" object:nil];
}
#pragma mark - 订单列表
- (void)getGoodsListData
{
    NSString *status;
    if (self.selectIndex == 0) {
        status = @"";
    } else {
        status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex];
    }
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=orderlist&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=1&status=%@&type=1",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        self.dataArray = [NSMutableArray array];
        self.currentPage = 1;
        if ([responseObject[@"status"] intValue] == 1) {
            self.dataArray = [OrderModel mj_objectArrayWithKeyValuesArray:responseObject[@"OrderList"]];
        }
        NSInteger i = [responseObject[@"OrderCount"] intValue]/self.pageSize;
        NSInteger j = [responseObject[@"OrderCount"] intValue]%self.pageSize;
        NSInteger n = 0;
        if (j > 0) {
            n = i+1;
        } else {
            n = i;
        }
        if (n<2) {
            self.tableView.mj_footer.hidden = YES;
        } else {
            self.tableView.mj_footer.hidden = NO;
        }
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_header endRefreshing];
    }];
}
- (void)getGoodsListDataMore
{
    self.currentPage++;
    NSString *status;
    if (self.selectIndex == 0) {
        status = @"";
    } else {
        status = [NSString stringWithFormat:@"%ld",(long)self.selectIndex];
    }
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=orderlist&companyid=%@&code=%@&timestamp=%@&pagesize=%@&pageindex=%@&status=%@&type=1",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],[NSString stringWithFormat:@"%ld",(long)self.pageSize],[NSString stringWithFormat:@"%ld",(long)self.currentPage],status] parameters:nil success:^(id responseObject) {
        [self.tableView.mj_footer endRefreshing];
        [MBProgressHUD hideHUDForView:self.view];
        if ([responseObject[@"status"] intValue] == 1) {
            
            NSInteger i = [responseObject[@"OrderCount"] intValue]/self.pageSize;
            NSInteger j = [responseObject[@"OrderCount"] intValue]%self.pageSize;
            NSInteger n = 0;
            if (j > 0) {
                n = i+1;
            } else {
                n = i;
            }
            if (self.currentPage > n) {
                self.currentPage--;
                self.tableView.mj_footer.hidden = YES;
            } else {
                self.tableView.mj_footer.hidden = NO;
                self.dataArray = (NSMutableArray *)[self.dataArray arrayByAddingObjectsFromArray:[OrderModel mj_objectArrayWithKeyValuesArray:responseObject[@"OrderList"]]];
                [self.tableView reloadData];
            }
        } else {
            self.currentPage--;
            self.tableView.mj_footer.hidden = YES;
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        [self.tableView.mj_footer endRefreshing];
    }];
}
- (void)setUpUI
{
    [self addSegment];
    
    [self.view addSubview:self.tableView];
}
#pragma mark - 分段选择
- (void)addSegment
{
    // 采购订单
    NSArray *title_arr = @[@"全部",@"待付款",@"待发货",@"待收货",@"已签收"];
    self.topSView = [SGSegmentedControlStatic segmentedControlWithFrame:CGRectMake(0, SafeAreaTopHeight, kScreenWidth, rateHeight(90)) delegate:self childVcTitle:title_arr indicatorIsFull:NO];
    _topSView.backgroundColor = UIColorWhite;
    // 必须实现的方法
    [self.topSView SG_setUpSegmentedControlType:^(SGSegmentedControlStaticType *segmentedControlStaticType, NSArray *__autoreleasing *nomalImageArr, NSArray *__autoreleasing *selectedImageArr) {
    }];
    [self.view addSubview:_topSView];
    _topSView.selectedIndex = self.selectIndex1;
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90), kScreenWidth, rateHeight(10))];
    line.backgroundColor = tableViewBgColor;
    [self.view addSubview:line];
}
#pragma mark - segment delegate
- (void)SGSegmentedControlStatic:(SGSegmentedControlStatic *)segmentedControlStatic didSelectTitleAtIndex:(NSInteger)index {
    if (segmentedControlStatic == _topSView) {

        self.selectIndex = index;
        NSLog(@"index - - %ld", (long)index);
        [self getGoodsListData];
    }
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[section];
        return model.OrderGoodsList.count;
    } else {
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderTableViewCell *cell = [[OrderTableViewCell alloc] init];
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[indexPath.section];
        NSArray *array = model.OrderGoodsList;
        NSDictionary *dic = array[indexPath.row];
        [cell.goodsImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"CartImg"]]]];
        cell.goodsTitleLB.text = dic[@"CommodityName"];
        cell.describeLB.text = dic[@"CommodityProperty"];
        cell.numLB.text = [NSString stringWithFormat:@"×%@",dic[@"CommodityNumber"]];
        cell.priceLB.hidden = YES;
    }
    cell.selectionStyle = NO;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return rateHeight(180);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return rateHeight(70);
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[section];
        if ([model.orderStatus intValue] == 2 || [model.orderStatus intValue] == 4) {
            return rateHeight(100);
        } else {
            return rateHeight(210);
        }
    } else {
        return 0.01;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *bgV = [[UIView alloc] init];
    bgV.backgroundColor = UIColorWhite;
    
    UILabel *label = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0x3b3b3b) fontSize:13];
    [label sizeToFit];
    [bgV addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.left.equalTo(bgV).offset(rateWidth(30));
    }];
    UILabel *label1 = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0xf55555) fontSize:13];
    [label1 sizeToFit];
    [bgV addSubview:label1];
    [label1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(bgV);
        make.right.equalTo(bgV).offset(-rateWidth(30));
    }];
    // 赋值
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[section];
        label.text = [NSString stringWithFormat:@"订单编号：%@",model.ordersNumber];
        label1.text = model.orderStatusName;
    }
    
    return bgV;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[section];
        if ([model.orderStatus intValue] == 2 || [model.orderStatus intValue] == 4) {
            UIView *bgV = [[UIView alloc] init];
            bgV.backgroundColor = tableViewBgColor;
            UIView *whiteV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(90))];
            whiteV.backgroundColor = UIColorWhite;
            [bgV addSubview:whiteV];
            UILabel *priceLB = [UILabel labelWithText:@"￥0.00" textColor:UIColorFromRGB(0xf55555) fontSize:13];
            [priceLB sizeToFit];
            [whiteV addSubview:priceLB];
            [priceLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(whiteV).offset(-rateWidth(30));
                make.top.equalTo(whiteV).offset(rateHeight(25));
            }];
            UILabel *heJiLB = [UILabel labelWithText:@"合计：" textColor:UIColorFromRGB(0x909090) fontSize:13];
            [heJiLB sizeToFit];
            [whiteV addSubview:heJiLB];
            [heJiLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(priceLB);
                make.right.equalTo(priceLB.mas_left);
            }];
            priceLB.text = [NSString stringWithFormat:@"￥%.2f",[model.orderTotalprice floatValue]];
            return bgV;
        } else {
            UIView *bgV = [[UIView alloc] init];
            bgV.backgroundColor = tableViewBgColor;
            UIView *whiteV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, rateHeight(200))];
            whiteV.backgroundColor = UIColorWhite;
            [bgV addSubview:whiteV];
            UILabel *priceLB = [UILabel labelWithText:@"￥0.00" textColor:UIColorFromRGB(0xf55555) fontSize:13];
            [priceLB sizeToFit];
            [whiteV addSubview:priceLB];
            [priceLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(whiteV).offset(-rateWidth(30));
                make.top.equalTo(whiteV).offset(rateHeight(25));
            }];
            UILabel *heJiLB = [UILabel labelWithText:@"合计：" textColor:UIColorFromRGB(0x909090) fontSize:13];
            [heJiLB sizeToFit];
            [whiteV addSubview:heJiLB];
            [heJiLB mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(priceLB);
                make.right.equalTo(priceLB.mas_left);
            }];
            UIButton *btn1 = [UIButton buttonWithTitle:@"" fontSize:15 titleColor:UIColorWhite background:navBarColor cornerRadius:3];
            [whiteV addSubview:btn1];
            [btn1 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(whiteV).offset(-rateWidth(30));
                make.size.mas_offset(CGSizeMake(rateWidth(180), rateHeight(70)));
                make.bottom.equalTo(whiteV).offset(-rateHeight(30));
            }];
            
            UIButton *btn2 = [UIButton buttonWithTitle:@"" fontSize:15 titleColor:UIColorFromRGB(0x3b3b3b) background:UIColorFromRGB(0xf5f5f5) cornerRadius:3];
            [whiteV addSubview:btn2];
            [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(btn1.mas_left).offset(-rateWidth(40));
                make.size.mas_offset(CGSizeMake(rateWidth(180), rateHeight(70)));
                make.centerY.equalTo(btn1);
            }];
            
            // 赋值
            if (_dataArray.count != 0) {
                OrderModel *model = _dataArray[section];
                priceLB.text = [NSString stringWithFormat:@"￥%.2f",[model.orderTotalprice floatValue]];
                if ([model.orderStatus intValue] == 1) {
                    // 待付款
                    [btn1 setTitle:@"支付" forState:(UIControlStateNormal)];
                    [btn2 setTitle:@"取消订单" forState:(UIControlStateNormal)];
                    
                    btn2.tag = section;
                    [btn2 addTarget:self action:@selector(quXiaoOrder:) forControlEvents:(UIControlEventTouchUpInside)];
                    
                    btn1.tag = section;
                    [btn1 addTarget:self action:@selector(zhiFuOrder:) forControlEvents:(UIControlEventTouchUpInside)];
                    
                } else if ([model.orderStatus intValue] == 2) {
                    // 待发货
                    
                } else if ([model.orderStatus intValue] == 3) {
                    // 待收货
                    [btn1 setTitle:@"确认收货" forState:(UIControlStateNormal)];
                    [btn2 setTitle:@"查看物流" forState:(UIControlStateNormal)];
                    
                    btn1.tag = section;
                    [btn1 addTarget:self action:@selector(queRenShouHuo:) forControlEvents:(UIControlEventTouchUpInside)];
                    btn2.tag = section;
                    [btn2 addTarget:self action:@selector(viewWuLiu:) forControlEvents:(UIControlEventTouchUpInside)];
                    
                } else if ([model.orderStatus intValue] == 4) {
                    // 已签收
                    [btn1 setTitle:@"售后" forState:(UIControlStateNormal)];
                    [btn1 addTarget:self action:@selector(shouHouAction) forControlEvents:(UIControlEventTouchUpInside)];
                    [btn2 setTitle:@"评价" forState:(UIControlStateNormal)];
                    [btn2 addTarget:self action:@selector(pingJiaAction) forControlEvents:(UIControlEventTouchUpInside)];
                }
            }
            return bgV;
        }
    } else {
        return nil;
    }
}
#pragma mark - 支付
- (void)zhiFuOrder:(UIButton *)btn
{
    if (self.dataArray.count != 0) {
        OrderModel *model = self.dataArray[btn.tag];
        ZhiFuViewController *zhiFuVC = [[ZhiFuViewController alloc] init];
        zhiFuVC.orderNumber = model.ordersNumber;
        zhiFuVC.payMoney = [NSString stringWithFormat:@"￥%.2f",[model.orderTotalprice floatValue]];
        zhiFuVC.payType = model.ordersZffs;
        [self.navigationController pushViewController:zhiFuVC animated:YES];
    }
}
#pragma mark - 取消订单
- (void)quXiaoOrder:(UIButton *)btn
{
    WeakSelf
    UIAlertController *alertController = [UIAlertController initWithMessage:@"是否取消订单？" bolck:^(void) {
        if (weakSelf.dataArray.count != 0) {
            OrderModel *model = weakSelf.dataArray[btn.tag];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:weakSelf.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=orderdelete&companyid=%@&code=%@&timestamp=%@&ordersNumber=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],model.ordersNumber] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [weakSelf.dataArray removeObject:model];
                    [weakSelf.tableView reloadData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:weakSelf.view message:@"网络不给力..."];
            }];
        }
    } cancelBolck:^(void) {
        
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 确认收货
- (void)queRenShouHuo:(UIButton *)btn
{
    WeakSelf
    UIAlertController *alertController = [UIAlertController initWithMessage:@"是否确认收货？" bolck:^(void) {
        if (weakSelf.dataArray.count != 0) {
            OrderModel *model = weakSelf.dataArray[btn.tag];
            NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
            [MBProgressHUD showMessage:nil toView:weakSelf.view];
            [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/order.ashx?action=ordershouhuo&companyid=%@&code=%@&timestamp=%@&ordersNumber=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],model.ordersNumber] parameters:nil success:^(id responseObject) {
                [MBProgressHUD hideHUDForView:weakSelf.view];
                if ([responseObject[@"status"] intValue] == 1) {
                    [weakSelf.dataArray removeObject:model];
                    [weakSelf.tableView reloadData];
                }
                
            } failure:^(NSError *error) {
                [TFHUD addRemindHUD:weakSelf.view message:@"网络不给力..."];
            }];
        }
    } cancelBolck:^(void) {
        
    }];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 查看物流
- (void)viewWuLiu:(UIButton *)btn
{
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[btn.tag];
        WuLiuInfoViewController *wuLiuInfoVC = [[WuLiuInfoViewController alloc] init];
        wuLiuInfoVC.ordersnumber = model.ordersNumber;
        wuLiuInfoVC.wuLiuInfo = model.orderDeliveryInfo;
        [self.navigationController pushViewController:wuLiuInfoVC animated:YES];
    }
    
}
#pragma mark - 售后
- (void)shouHouAction
{
    ShouHouViewController *shouHouVC = [[ShouHouViewController alloc] init];
    [self.navigationController pushViewController:shouHouVC animated:YES];
}
#pragma mark - 评价
- (void)pingJiaAction
{
    PingJiaViewController *pingJiaVC = [[PingJiaViewController alloc] init];
    [self.navigationController pushViewController:pingJiaVC animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_dataArray.count != 0) {
        OrderModel *model = _dataArray[indexPath.section];
        OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
        orderDetailVC.ordersNumber = model.ordersNumber;
        [self.navigationController pushViewController:orderDetailVC animated:YES];
    }
}
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight+rateHeight(90)+rateHeight(10), kScreenWidth, kScreenHeight-SafeAreaTopHeight-rateHeight(90)-rateHeight(10)) style:(UITableViewStyleGrouped)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        WeakSelf
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf getGoodsListData];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [weakSelf getGoodsListDataMore];
        }];
    }
    return _tableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
